package com.example.test.comutil;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;

import androidx.annotation.RequiresApi;

import com.puty.conputyutils.bean.FileBean;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件类处理工具
 */
public class FileManagerUtils {
    /**Excel类型*/
    public static final int TYPE_EXCEL = 0;
    /**apk类型*/
    public static final int TYPE_APK = 1;
    /**压缩包类型*/
    public static final int TYPE_ZIP = 2;


    private static FileManagerUtils mInstance;
    public static ContentResolver mContentResolver;
    private static Object mLock = new Object();

    public static FileManagerUtils getInstance(){
        if (mInstance == null){
            synchronized (mLock){
                if (mInstance == null){
                    mInstance = new FileManagerUtils();
                    mContentResolver = LeoUtils.getApplication().getContentResolver();
                }
            }
        }
        return mInstance;
    }

    /**
     * 判断文件是否存在
     * @param path 文件的路径
     * @return true 为存在 false为不存在
     */
    public static boolean isExists(String path) {
        File file = new File(path);
        return file.exists();
    }

    /**
     * 通过文件类型得到相应文件的集合
     * @param fileType 文件类型
     * @return 文件的集合
     */
    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
    public List<FileBean> getFilesByType(int fileType) {
        List<FileBean> files = new ArrayList<FileBean>();
        // 扫描files文件库
        Cursor c = null;
        try {
            c = mContentResolver.query(MediaStore.Files.getContentUri("external"), new String[]{"_id", "_data", "_size"}, null, null, null);
            int dataindex = c.getColumnIndex(MediaStore.Files.FileColumns.DATA);
            int sizeindex = c.getColumnIndex(MediaStore.Files.FileColumns.SIZE);

            while (c.moveToNext()) {
                String path = c.getString(dataindex);

                if (getFileType(path) == fileType) {
                    if (!isExists(path)) {
                        continue;
                    }
                    long size = c.getLong(sizeindex);
                    String fileName = "";
                    if(!TextUtils.isEmpty(path)){
                        String[] split = path.split("/");
                        fileName = split[split.length-1];
                    }
                    FileBean fileBean = new FileBean(fileName, path);
                    files.add(fileBean);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return files;
    }

    /**
     * 获取文件类型
     *
     * @param path 文件路径
     * @return 文件类型
     */
    public static int getFileType(String path) {
        path = path.toLowerCase();
        //|| path.endsWith(".ppt") || path.endsWith(".pptx") || path.endsWith(".doc") || path.endsWith(".docx")
        if ( path.endsWith(".xls") || path.endsWith(".xlsx")) {
            return TYPE_EXCEL;
        }else if (path.endsWith(".apk")) {
            return TYPE_APK;
        }else if (path.endsWith(".zip") || path.endsWith(".rar") || path.endsWith(".tar") || path.endsWith(".gz")) {
            return TYPE_ZIP;
        }else{
            return -1;
        }
    }

    /**
     * 保存文件
     * @param str 内容
     * @param fileName 文件名称
     */
    public static void saveFile(String str,String fileName) {
        String path = Environment.getExternalStorageDirectory() + "/Download/" + fileName;
        try {
            FileOutputStream fou = new FileOutputStream(path);
            fou.write(str.getBytes(),0 ,str.getBytes().length);
            fou.close();
            File file = new File(path);
            Uri data = Uri.parse("file:///" + file.getAbsolutePath());
            LeoUtils.getApplication().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, data));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
